package com.daniel.thingofday;

import java.io.BufferedReader;
import android.view.GestureDetector.SimpleOnGestureListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

public class listOfRecent extends Activity{
Button toMain;
TextView listText;
WebView showThePage;
String url;
private static final int LARGE_MOVE = 60;
int dayToShow = 1;
private GestureDetector gestureDetector;
GetThingOfDayActivity mainClass = new GetThingOfDayActivity();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		Intent recieve = getIntent();
		showThePage = (WebView) findViewById(R.id.web_engineList);
		showThePage.setWebViewClient(new WebC());
		final int month = recieve.getIntExtra("month", 0) + 1;
		final int year = recieve.getIntExtra("year", 0);
		toMain = (Button) findViewById(R.id.toMain);
		listText = (TextView) findViewById(R.id.listText);
		String setText = connect("http://mcauthserv.net76.net/TOD.json", month, year);
		listText.setText(setText);
		gestureDetector = new GestureDetector(this, new SimpleOnGestureListener(){
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
			{
				if(e1.getX() - e2.getX() > LARGE_MOVE)
				{
					dayToShow++;
					String setText = connect("http://mcauthserv.net76.net/TOD.json", month, year);
					listText.setText(setText);
					return true;
				}
				else if(e2.getX() - e1.getX() > LARGE_MOVE)
				{
					//right
					dayToShow--;
					String setText = connect("http://mcauthserv.net76.net/TOD.json", month, year);
					listText.setText(setText);
					return true;
				}
				return false;
			}
		});
		toMain.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent toMain = new Intent(listOfRecent.this, GetThingOfDayActivity.class);
				startActivity(toMain);
				finish();
			}
		});
		
	}



public String connect(String url, int month, int year)
{
    // Create the httpclient
    HttpClient httpclient = new DefaultHttpClient();
   
    // Prepare a request object
    HttpGet httpget = new HttpGet(url);
    httpget.setHeader("Cache-Control", "no-cache");
    // Declare a response
    HttpResponse response;
 
    // Declare a return string
    String returnString = null;
    try {
    	 
        // Open the webpage.
        response = httpclient.execute(httpget);

        if(response.getStatusLine().getStatusCode() == 200){
            // Connection was established. Get the content. 

            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {
                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();
                    // Load the requested page converted to a string into a JSONObject.
                    JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
            returnString = "";
            if (entity != null) {
            	    JSONObject data = jsonResponse.getJSONObject(month+"/"+dayToShow+"/"+year);
            	    FileOutputStream fos = openFileOutput("ThingOfDayCache", Context.MODE_PRIVATE);
            	    fos.write(jsonResponse.toString().getBytes());
            	    fos.close();
            	    //JSONObject data = jsonResponse.getJSONObject("7/27/2012");
            	    returnString += "The thing for "+ month + "/" + dayToShow + "/" + year + "  is: ";
            		for (int i1 = 1; i1 < data.length(); i1++) {
            			returnString += "\n\t" + data.getString(""+i1);
                		if(URLUtil.isValidUrl(data.getString(""+i1)))
                		{
                			url = data.getString(""+i1);
                			showThePage.loadUrl(url);
                		}
            		}
            		
            	}
            }
        else {
            // code here for a response othet than 200.  A response 200 means the webpage was ok
            // Other codes include 404 - not found, 301 - redirect etc...
            // Display the response line.
            returnString = "Unable to load page - " + response.getStatusLine();
        }
    }
    }
    
    catch (IOException  ex) {
        // thrown by line 80 - getContent();
        // Connection was not established
        returnString = "Connection failed; " + ex.getMessage();
    }
    catch (JSONException ex){
        // JSON errors
        returnString = "JSON failed; " + ex.getMessage();
    }
    return returnString;
    }
    
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
    
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
    	return gestureDetector.onTouchEvent(event);
    }
}